﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using MySql.Data.MySqlClient;
using LdExpress;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
    public string ContainerPage = "./FormDocuments.aspx";
    public string strCondition = "";
    public int NumOfItemsPerPage = 100;
    public string strPager = "";
    public string strError = "";
    public string strMess = "";
    public string type = "";
    public string strProcessName = "";
    public int nPermissions = 0;

    protected void Page_Load(object sender, EventArgs e)
    {
        int nPage = 1;
        string strPageID = "page_number";
        if (Request.QueryString["type"] != "")
            type = Request.QueryString["type"].ToString();
        else
            type = "0";
        switch (type)
        {
            case "1":
                strProcessName = "CUS";
                break;
            case "2":
                strProcessName = "DOC";
                break;
            case "3":
                strProcessName = "SALES";
                break;
            case "4":
                strProcessName = "ACCNT";
                break;
        }
        try
        {

            if (Request.QueryString[strPageID] != null)
                nPage = int.Parse(Request.QueryString[strPageID]);
        }
        catch
        {
            nPage = 1;
        }
        if (nPage <= 0) nPage = 1;

        if (Session["logined_id"] != null)
        {
            if (type == "1")
            {
                if (Session["formcus"] != "") nPermissions = int.Parse(Session["formcus"].ToString());
            }
            else if (type == "2")
            {
                if (Session["formdoc"] != "") nPermissions = int.Parse(Session["formdoc"].ToString());
            }
            else if (type == "3")
            {
                if (Session["formsales"] != "") nPermissions = int.Parse(Session["formsales"].ToString());
            }
            else if (type == "4")
            {
                if (Session["formaccnt"] != "") nPermissions = int.Parse(Session["formaccnt"].ToString());
            }
            if (nPermissions <= 0) Response.Redirect("Login.aspx");
        }
        else
            Response.Redirect("Login.aspx");

        if (!Page.IsPostBack)
        {
            if (Request.QueryString["action"] == "delete" && nPermissions > 7)
            {
                FormDocuments obj = new FormDocuments();
                obj.ID = long.Parse(Request.QueryString["PortsID"]);
                obj.Load(GV.cn, GV.trans);
                obj.Delete(GV.cn, GV.trans);
                Response.Redirect("FormDocuments.aspx?type=" + type + ((Request.QueryString["page_number"] != null && Request.QueryString["page_number"].ToString() != "") ? "page_number=" + Request.QueryString["page_number"].ToString() : ""));
            }
            else
            {
                if (Request.QueryString["ID"] != null)
                {
                    loadProcessJob();
                }
            }

            #region Build List
            int nNumOfPages = 0;

            DataTable dtList;
            BuildList(NumOfItemsPerPage, nPage, out nNumOfPages, out dtList, null, null);
            if (nPage > nNumOfPages) nPage = 1;

            rptData.DataSource = dtList;
            rptData.DataBind();
            #endregion
            #region Build Pager
            CommonFunctions.BuildPager(Request, nNumOfPages, nPage, strPageID, ContainerPage, out strPager);
            #endregion
        }

    }
    protected void loadProcessJob()
    {
        FormDocuments obj = new FormDocuments();
        obj.ID = long.Parse(Request.QueryString["ID"]);
        obj.Load(GV.cn, GV.trans);
        txtName.Text = HttpUtility.HtmlDecode(obj.Name);
        txtDescription.Text = obj.Description;
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        strError = "";
        strMess = "";
        string serverFileName = "";
        string strType = "";
        FormDocuments obj = new FormDocuments();
        obj.ID = -1;
        if (Request.QueryString["ID"] != null)
        {
            obj.ID = long.Parse(Request.QueryString["ID"]);
            obj.Load(GV.cn, GV.trans);
        }
        if (Request.QueryString["type"] != null)
        {
            obj.Type = long.Parse(Request.QueryString["type"].ToString());
            strType = "type=" + Request.QueryString["type"].ToString();
        }
        if (txtName.Text == "")
        {
            strError = "NotBlank";
            strMess = "Tên tài liệu không để trống!";
        }
        if (FileInput.PostedFile.FileName == "")
        {
            lblInfo.Text = "No file specified.";
        }
        else
        {
            try
            {
                serverFileName = Path.GetFileName(FileInput.PostedFile.FileName);
                string ext = Path.GetExtension(serverFileName);
                if (ext == ".doc" || ext == ".xls" || ext == ".docx" || ext == ".xlsx")
                {
                    string strPath = MapPath(".") + "\\FormDocuments\\";
                    FileInput.PostedFile.SaveAs(strPath + serverFileName);
                    //lblInfo.Text = "File " + serverFileName;
                    //lblInfo.Text += " uploaded successfully.";
                    obj.Location = serverFileName;
                }
                else
                {
                    strError = "File not specified";
                    strMess = "Chỉ được upload fie wolds và exel!";
                }

            }
            catch (Exception err)
            {
                lblInfo.Text = err.Message;
            }
        }


        if (strError == "")
        {
            obj.Name = txtName.Text.Trim();
            obj.Description = txtDescription.Text.Trim();
            obj.LastUpdate = DateTime.Now;
            obj.Save(GV.cn, GV.trans);
            Response.Redirect("FormDocuments.aspx?" + strType + ((Request.QueryString["page_number"] != null && Request.QueryString["page_number"].ToString() != "") ? "&page_number=" + Request.QueryString["page_number"].ToString() : ""));
        }
        else
        {
            lblInfo.Text = strMess;
        }
    }

    private void BuildList(int NumOfItemsPerPage, int PageNo, out int nNumOfPages, out DataTable dtList, MySqlConnection cn, MySqlTransaction trans)
    {
        DataSet ds = null;
        dtList = new DataTable();
        dtList.Columns.Add("Sort");
        dtList.Columns.Add("Index");
        dtList.Columns.Add("Name");
        dtList.Columns.Add("Location");
        dtList.Columns.Add("Description");
        dtList.Columns.Add("LastUpdate");
        dtList.Columns.Add("Action");
        //Get List by SoIDs
        nNumOfPages = 0;
        if (Request.QueryString["type"] != null)
            strCondition = " and Type=" + Request.QueryString["type"].ToString();
        else
            strCondition = " and 0=1";
        FormDocuments obj = new FormDocuments();
        obj.GetList(strCondition, "", NumOfItemsPerPage, PageNo, out nNumOfPages, out ds, GV.cn, GV.trans);

        string strAllQueryString = "";
        foreach (string strKey in Request.QueryString.AllKeys)
        {
            if (strKey != null)
            {
                if ((strKey.ToLower() != "action") && (strKey.ToLower() != "id"))
                    strAllQueryString = strAllQueryString + "&" + strKey + "=" + Request.QueryString[strKey].ToString();
            }
        }

        if (strAllQueryString.Length >= 1)
            strAllQueryString = strAllQueryString.Substring(1);

        if (ds != null)
        {
            int count = 0;
            if (Request.QueryString["page_number"] != null && Request.QueryString["page_number"].ToString() != "")
            {
                int pagenumber = 1;
                try
                {
                    pagenumber = int.Parse(Request.QueryString["page_number"]);
                    count = NumOfItemsPerPage * (pagenumber - 1);
                }
                catch { count = 0; }
            }
            foreach (DataRow dr in ds.Tables[0].Rows)
            {

                count++;
                string strSTT = dr["Sort"].ToString();
                string strIndex = count.ToString();
                string strName = dr["Name"].ToString();
                if (nPermissions >= 3)
                    strName = "<a href=\"FormDocuments.aspx?type=" + type + "&ID=" + dr["ID"].ToString() + ((Request.QueryString["page_number"] != null && Request.QueryString["page_number"].ToString() != "") ? "&page_number=" + Request.QueryString["page_number"].ToString() : "") + "\">" + strName + "</a>";
                string strDescripton = dr["Description"].ToString();
                string strLastUpdate = dr["LastUpdate"].ToString();
                if (dr["LastUpdate"].ToString() != "")
                {
                    strLastUpdate = DateTime.Parse(dr["LastUpdate"].ToString()).ToString("ddMMyyyy");
                }
                string strLocation = dr["Location"].ToString();
                if (strLocation.Length > 0)
                {
                    strLocation = "<a href=\"/FormDocuments/" + strLocation + "\">Download</a>";

                }
                string strAction = "";
                if (nPermissions >= 3)
                    strAction = "<a href=\"FormDocuments.aspx?type=" + type + "&ID=" + dr["ID"].ToString() + ((Request.QueryString["page_number"] != null && Request.QueryString["page_number"].ToString() != "") ? "&page_number=" + Request.QueryString["page_number"].ToString() : "") + "\">Edit</a>";
                if (nPermissions > 7)
                    strAction += " - <a href=\"javascript:doDelete('" + System.Web.HttpUtility.HtmlEncode(dr["ID"].ToString()) + "'," + System.Web.HttpUtility.HtmlEncode(type) + ")\">" + "Delete</a>";
                //strEditProfile = "<a href=\"../DangKyCVC/ThongTinChungDKCVC.aspx?DangKyCVCID=" + dr["ID"].ToString() + "\">Sửa</a>";

                string[] strValues = new string[] { strSTT, strIndex, strName, strLocation, strDescripton, strLastUpdate, strAction };
                dtList.Rows.Add(strValues);
            }
        }
    }
}
